<?php

namespace app\admin\model\ldcms;

use addons\ldcms\model\common\Backend;
use addons\ldcms\utils\AutoSql;
use app\common\library\Menu;
use Exception;
use think\Db;
use tool\dir;


class Models extends Backend
{
    // 表名
    protected $name = 'ldcms_models';
    protected $sort='id DESC';

    // 追加属性
    protected $append = [
        'create_time_text',
        'update_time_text',
        'status_text'
    ];

    protected static function init() {
        /*新增前回调*/
        self::beforeInsert(function ($data) {
            if (!preg_match("/^([a-z0-9_]+)$/", $data['table_name'])) {
                throw new Exception("表名只支持小写字母、数字、下划线");
            }
            $autoSql = AutoSql::instance();
            $table='ldcms_document_'.$data['table_name'];
            $res=$autoSql->checkTable($table);
            if($res){
                throw new Exception($table.' 表已存在');
            }
            $autoSql->createTable($table,$data['name'],'document_id','',false);
        });

        self::afterInsert(function ($data){
            /*创建菜单*/
            $menu=[
                [
                    'name'    => "ldcms/document/index/mid/{$data['id']}",
                    'title'   => $data['name'].'内容',
                    'remark'  => $data['name'].'内容管理',
                    'icon'    => 'fa fa-list-alt',
                    'ismenu'  => 1,
                    'weigh'   => $data['id']
                ]
            ];
            Menu::create($menu,'ldcms/document');
        });

        self::beforeUpdate(function ($data){
            /*更新菜单*/
            $row=self::find($data['id']);
            if($row['name']!=$data['name']){
                $menu=[
                    [
                        'name'=>'ldcms',
                        'title'=>'LDCMS',
                        'sublist'=>[
                            [
                                'name'=>'ldcms/document',
                                'title'=>'内容管理',
                                'sublist'=>[
                                    [
                                        'name'    => "ldcms/document/index/mid/{$data['id']}",
                                        'title'   => $data['name'].'内容',
                                        'remark'  => $data['name'].'内容管理',
                                        'ismenu'  => 1,
                                    ]
                                ]
                            ]

                        ]
                    ]
                ];
                Menu::upgrade('ldcms',$menu);
            }
            if (!$data['status']) {
                $data['ismenu'] = 0;
            }
            /*更新状态*/
            if($data['ismenu']==0){
                Menu::disable("ldcms/document/index/mid/{$data['id']}");
            }

            if($data['ismenu']==1){
                $ids=Menu::getAuthRuleIdsByName("ldcms/document/index/mid/{$data['id']}");
                if(empty($ids)){
                    /*创建菜单*/
                    $menu=[
                        [
                            'name'    => "ldcms/document/index/mid/{$data['id']}",
                            'title'   => $data['name'].'内容',
                            'remark'  => $data['name'].'内容管理',
                            'icon'    => 'fa fa-list-alt',
                            'ismenu'  => 1,
                            'weigh'   => $data['id']
                        ]
                    ];
                    Menu::create($menu,'ldcms/document');
                }else{
                    Menu::enable("ldcms/document/index/mid/{$data['id']}");
                }
            }
        });

        self::beforeDelete(function ($data){
            Db::name('ldcms_fields')->where('mid',$data['id'])->delete();
            Menu::delete("ldcms/document/index/mid/{$data['id']}");
        });
    }

    public function getStatusTextAttr($value,$data)
    {
        $status=[0=>'关闭',1=>'启用'];
        return $status[$data['status']];
    }

    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['create_time']) ? $data['create_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getUpdateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['update_time']) ? $data['update_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getAdminList()
    {
        return $this->where('status',1)->order($this->sort)->column('id,name,table_name,template_list,template_detail','id');
    }

    /**
     * 获取模板
     * @param string $path
     * @return array|void
     * @Author: wusn <958342972@qq.com>
     * @DateTime: 11/27/20 11:51 AM
     */
    public function getTpl($type='list')
    {
        $config=get_site_config(get_lang());
        $base_path=ADDON_PATH.'ldcms'.DS.'view'.DS.$config['template'].DS;
        //列出文件夹下的所有文件
        $dir=new \addons\ldcms\utils\Dir($base_path);
        $files=$dir->toArray();
        $filenames=[];
        foreach ($files as $file){
            if(strpos($file['filename'],$type.'_')!==false){
                $filenames[]=[
                    'id'=>$file['filename'],
                    'title'=>$file['filename']
                ];
            }
        }
        return $filenames;
    }

}
